package encryption;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Base64;

/**
 * Md5加密,不可逆的加密
 *
 * @author 张峰浦
 * @create 创建时间：2020-01-15 9:56
 */
public class Md5Until {
    /**
     * 简单的MD5加密<br/>
     * 直接用Base64和md5处理明文string，得到一个简单加密的密文
     *
     * @param password 需加密的明文string
     * @return 处理后的密文string
     */
    public static String md5(String password) {
        try {
            MessageDigest md = MessageDigest.getInstance("md5");

            //生成随机东东 不可逆
            byte[] bytes = md.digest(password.getBytes());

            String str = Base64.getEncoder().encodeToString(bytes);

            return str;
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * MD5加码 生成32位md5码
     *
     * @param inStr 需加密的明文string
     * @return 处理后的密文string
     */
    private static String set2Md5(String inStr) {
        MessageDigest md5 = null;
        try {
            md5 = MessageDigest.getInstance("MD5");
        } catch (Exception e) {
            System.out.println(e.toString());
            e.printStackTrace();
            return "";
        }
        char[] charArray = inStr.toCharArray();
        byte[] byteArray = new byte[charArray.length];

        for (int i = 0; i < charArray.length; i++) {
            byteArray[i] = (byte) charArray[i];
        }
        byte[] md5Bytes = md5.digest(byteArray);
        StringBuffer hexValue = new StringBuffer();

        for (int i = 0; i < md5Bytes.length; i++) {
            int val = ((int) md5Bytes[i]) & 0xff;
            if (val < 16) {
                hexValue.append("0");
            }
            hexValue.append(Integer.toHexString(val));
        }
        return hexValue.toString();

    }

    /**
     * 二次加密MD5<br/>
     * 主动增加字符串复杂度
     *
     * @param inStr 需加密的明文string
     * @return 处理后的明文string
     */
    public static String setMd5(String inStr) {
        String xy = "$$";
        String finalStr = "";
        if (inStr != null) {
            String fStr = inStr.substring(0, 1);
            String lStr = inStr.substring(1, inStr.length());
            finalStr = set2Md5(fStr + xy + lStr);

        } else {
            finalStr = set2Md5(xy);
        }
        return finalStr;
    }

}